package com.learn.justauth;

import java.io.IOException;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletResponse;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;


@RestController
@RequestMapping("/oauth")
public class RestAuthController {

    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    @RequestMapping("/callback")
    public Object login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        AuthResponse<AuthUser> response = authRequest.login(callback);
        JSONObject jsonObject = JSONUtil.parseObj(response, false);

        AuthUser data = response.getData();
        return data;
    }

    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(
            AuthConfig.builder()
                .clientId("280ca20d556e2e42086611d45835b2fe626aa357f2a41545cc5e12ec20f69468")
                .clientSecret("0bc626bb269f2808db86cdced411f7c66386bf8e22fceb7e551ffdb8469013a3")
                .redirectUri("http://localhost:8989/oauth/callback")
                .build()
         );
    }
}
